import {
  _decorator,
  Component,
  Node,
  Sprite,
  UITransform,
  Animation,
  AnimationClip,
  animation,
  Vec3,
  SpriteFrame,
  debug,
} from 'cc'
import { TILE_HEIGHT, TILE_WIDTH } from '../Scripts/Tile/TileManage'
import ResourceManage from '../Runtime/resourceManage'
import {
  CONTROLLER_ENUM,
  DIRECTION_ENUM,
  DIRECTION_ORDER_ENUM,
  ENTITY_STATE_ENUM,
  ENTITY_TYPE_ENUM,
  EVENT_ENUM,
  PARAMS_NAME_ENUM,
} from '../Enums'
import EventManage from '../Runtime/eventManage'
import { EntityManage } from '../Base/EntityManage'
import DataManage from '../Runtime/dataManage'
import { EnemyManage } from '../Base/EnemyManage'
import { BurstStateMachine } from './BurstStateMachine'
const { ccclass, property } = _decorator

@ccclass('BurstManage')
export class BurstManage extends EntityManage {
  async init(params) {
    // 初始化人物动画状态机
    this.fsm = this.addComponent(BurstStateMachine)
    await this.fsm.init()
    super.init(params)

    const transform = this.getComponent(UITransform)
    transform.setContentSize(TILE_WIDTH, TILE_HEIGHT)

    // 监听玩家移动，改变敌人朝向
    EventManage.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onBurst, this)
  }
  protected update(dt: number): void {
    this.node.setPosition(this.x * TILE_WIDTH, -this.y * TILE_HEIGHT)
  }
  onDestroy() {
    super.onDestroy()
    EventManage.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onBurst)
  }
  onBurst() {
    if (this.state === ENTITY_STATE_ENUM.DEATH) return
    const { x: playerX, y: playerY } = DataManage.Instance.player
    // 如果玩家在陷阱上，就触发攻击状态
    if (this.x === playerX && this.y === playerY && this.state === ENTITY_STATE_ENUM.IDLE) {
      this.state = ENTITY_STATE_ENUM.ATTACK
    } else if (this.state === ENTITY_STATE_ENUM.ATTACK) {
      this.state = ENTITY_STATE_ENUM.DEATH
      if (this.x === playerX && this.y === playerY) {
        EventManage.Instance.emit(EVENT_ENUM.ATTACK_PLAYER, ENTITY_STATE_ENUM.AIRDEATH)
      }
    }
  }
}
